﻿using Musi.Core.CSV;
using System;

namespace Musi
{
    [System.Serializable]
    public class ChartTime: ICSVParse<ChartTime>
    {
        public int hours;
        public int minutes;
        public float seconds;

        public ChartTime()
        {
            hours = 0;
            minutes = 0;
            seconds = 0;
        }

        public ChartTime(int hours, int minutes, float seconds)
        {
            this.hours = hours;
            this.minutes = minutes;
            this.seconds = seconds;
        }

        public ChartTime CorrectTime()
        {
            minutes += (int)(seconds / 60.0f);
            seconds %= 60.0f;

            hours += minutes / 60;
            minutes %= 60;

            return this;
        }

        public void ClearTime()
        {
            hours = 0;
            minutes = 0;
            seconds = 0;
        }

        public float ToSeconds()
        {
            return (hours * 60 + minutes) * 60 + seconds;
        }

        public ChartTime CSVParse(string src)
        {
            if (src == null || src.Trim() == "")
                return null;

            string[] time = src.Trim().Split(':');
            seconds = Convert.ToSingle(time[time.Length - 1]);
            if (time.Length > 1)
            {
                minutes = Convert.ToInt32(time[time.Length - 2]);
                if (time.Length > 2)
                {
                    hours = Convert.ToInt32(time[time.Length - 3]);
                }
            }

            return CorrectTime();
        }

        public bool Equals(ChartTime obj)
        {
            return Math.Abs(obj.seconds - seconds) <= 0.01f && obj.minutes == minutes && obj.hours == hours;
        }

        public override string ToString()
        {
            return $"{hours}:{minutes}:{string.Format("{0:f2}",seconds)}";
        }

        public static float operator -(ChartTime obj, ChartTime rhs)
        {
            return obj.ToSeconds() - rhs.ToSeconds();
        }
    }
}
